package com.atguigu04.other.dynamic;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDynamicTest {

    public Person getInstance() {

        return new Person();
    }

    //动态性
    public <T> T getInstance(String className) throws Exception {

        Class<?> clazz = Class.forName(className);
        Constructor<?> declaredConstructor = clazz.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        return (T)declaredConstructor.newInstance();
    }


    public Object invoke(String className,String methodName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {

        Class<?> aClass = Class.forName(className);
        Constructor<?> declaredConstructor = aClass.getDeclaredConstructor();
        declaredConstructor.setAccessible(true);
        Object o = declaredConstructor.newInstance();

        Method declaredMethod = aClass.getDeclaredMethod(methodName);
        declaredMethod.setAccessible(true);

        return declaredMethod.invoke(o);
    }
}
